package com.taiji.dianthus.controller.sms;

import com.alibaba.fastjson.JSONArray;
import com.taiji.dianthus.common.BasicController;
import com.taiji.dianthus.common.BusinessMessage;
import com.taiji.dianthus.domain.sms.SmsBackInfo;
import com.taiji.dianthus.domain.sms.SmsGroup;
import com.taiji.dianthus.domain.sms.SmsInfo;
import com.taiji.dianthus.domain.sms.SmsMoInfo;
import com.taiji.dianthus.domain.sys.DSysUser;
import com.taiji.dianthus.service.sms.SmsBackInfoService;
import com.taiji.dianthus.service.sms.SmsGroupService;
import com.taiji.dianthus.service.sms.SmsInfoService;
import com.taiji.dianthus.service.sms.SmsMoInfoService;
import com.taiji.dianthus.service.sys.OrgService;
import com.taiji.dianthus.service.sys.SysLogService;
import com.taiji.dianthus.util.IPUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.taiji.dianthus.common.Constant.*;

/**
 * @ClassName smsInfoController
 * @Description
 * @Author H.M
 * @Date 2020/7/15
 */
@RequestMapping(value = "/sms/info")
@Controller
public class SmsInfoViewController extends BasicController {

    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private SmsInfoService smsInfoService;
    @Autowired
    private SmsBackInfoService backInfoService;
    @Autowired
    private SmsMoInfoService moInfoService;


    @Autowired
    private SmsGroupService groupService;

    @ResponseBody
    @RequestMapping("/sendMsg")
    public BusinessMessage sendMsg(HttpServletRequest request, @RequestBody SmsInfo smsInfo) {
        smsInfo.setSendUserId(currentUser().getId());
        smsInfo.setMsgLoc(1);
        smsInfo.setMsgType(1);
        BusinessMessage message = smsInfoService.sendDSMS(smsInfo);
        sysLogService.save(currentUser(), LOG_OPERATION_SAVE,
                IPUtil.getIpAddr(request), "发送短信息", message.success ? 1 : 0, message.getMsg());
        return message;
    }

    @ResponseBody
    @RequestMapping("/saveDraft")
    public BusinessMessage saveDraft(HttpServletRequest request, @RequestBody SmsInfo smsInfo) {
        smsInfo.setSendUserId(currentUser().getId());
        smsInfo.setMsgLoc(2);
        smsInfo.setMsgType(1);
        BusinessMessage message = smsInfoService.save(smsInfo);
        sysLogService.save(currentUser(), LOG_OPERATION_SAVE,
                IPUtil.getIpAddr(request), "保存草稿", message.success ? 1 : 0, message.getMsg());
        return message;
    }

    /**
     * 群发定时短信
     *
     * @param request
     * @param smsInfo
     * @return
     */
    @ResponseBody
    @RequestMapping("/sendTimingMsg")
    public BusinessMessage sengTimingMsg(HttpServletRequest request, @RequestBody SmsInfo smsInfo) {
        smsInfo.setSendUserId(currentUser().getId());
        smsInfo.setMsgLoc(2);
        smsInfo.setMsgType(2);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(smsInfo.getMsgTime());
        calendar.set(Calendar.SECOND, 0);
        smsInfo.setMsgTime(calendar.getTime());
        BusinessMessage message = smsInfoService.save(smsInfo);
        // BusinessMessage message = sdk2SMSSendService.sendDSMS(smsInfo, false);
        sysLogService.save(currentUser(), LOG_OPERATION_SAVE,
                IPUtil.getIpAddr(request), "保存定时短信息", message.success ? 1 : 0, message.getMsg());
        return message;
    }

    /**
     * 已发送页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/list")
    public String sendMessageIndex(HttpServletRequest request, Model model, Integer pageSize, Integer currentPage, String startDate, String endDate) {
        try {
            currentPage = getCurrentPage(currentPage);
            pageSize = getPageSize(pageSize);
            DSysUser currentUser = currentUser();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
            String url = "/sms/info/list?pageSize=10";
            Date start = null;
            if (!StringUtils.isEmpty(startDate)) {
                url += "&startDate=" + startDate;
                model.addAttribute("startDate", startDate);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(simpleDateFormat.parse(startDate));
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                start = calendar.getTime();
            }
            Date end = null;
            if (!StringUtils.isEmpty(endDate)) {
                url += "&endDate=" + endDate;
                model.addAttribute("endDate", endDate);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(simpleDateFormat.parse(endDate));
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                end = calendar.getTime();
            }
            if (currentPage != null) {
                model.addAttribute("currentPage", currentPage + 1);
            }
            BusinessMessage message = smsInfoService.draftsList(currentPage, pageSize, start, end, currentUser.getId(), 1);
            model.addAttribute("url", url);
            model.addAttribute("data", message.getData());
            model.addAttribute("currentUser", currentUser);
            model.addAttribute("menus", listMenu());
            sysLogService.save(currentUser(), LOG_OPERATION_QUERY,
                    IPUtil.getIpAddr(request), "查询发件箱列表", message.success ? 1 : 0, message.getMsg());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "/pages/sms/smsSendList";
    }

    /**
     * 发件详情
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/one")
    public String getSmsOne(HttpServletRequest request, Model model, Integer currentPage, String startDate, String endDate, String id) {
        String pageUrl = "/pages/sms/smsSendOne";
        try {
            DSysUser currentUser = currentUser();
            String url = "/sms/info/list?pageSize=10";
            if (!StringUtils.isEmpty(startDate)) {
                url += "&startDate=" + startDate;
            }
            if (!StringUtils.isEmpty(endDate)) {
                url += "&endDate=" + endDate;
            }
            if (currentPage != null) {
                url += "&currentPage=" + currentPage;
            }
            SmsInfo info = smsInfoService.getOne(id);
            if (info.getMsgType() == 3 || (info.getMsgType() == 2 && !StringUtils.isEmpty(info.getSmsGroupId()))) {
                List<SmsGroup> groupList = groupService.getAllGroupNoPage(currentUser.getId());
                model.addAttribute("groupList", groupList);
                pageUrl = "/pages/sms/sendGroupOne";
            }
            //  List<SmsBackInfo> backInfos = backInfoService.getBySmsGroup(info.getId());
            List<SmsMoInfo> moInfoList = moInfoService.getBySmsInfoId(info.getId());
            model.addAttribute("moInfoList", moInfoList);
            model.addAttribute("url", url);
            model.addAttribute("data", info);
            model.addAttribute("currentUser", currentUser);
            model.addAttribute("menus", listMenu());
            sysLogService.save(currentUser(), LOG_OPERATION_QUERY,
                    IPUtil.getIpAddr(request), "跳转发件箱详情页面", 1, "查看发件箱详情");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageUrl;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public BusinessMessage delete(HttpServletRequest request, String id, Integer status) {
        BusinessMessage message = null;
        if (status != null) {
            message = smsInfoService.updateMsgLoc(id, status);
        } else {
            message = smsInfoService.deleteDrafts(id);
        }
        sysLogService.save(currentUser(), LOG_OPERATION_DEL,
                IPUtil.getIpAddr(request), "删除发件箱记录", message.success ? 1 : 0, message.getMsg());
        return message;
    }

    /**
     * 发件箱转发
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/forward")
    public String forwardSms(HttpServletRequest request, Model model, Integer currentPage, String startDate, String endDate, String id, String flag) {
        String pageUrl = "/pages/sms/forwardSms";
        SmsInfo info = new SmsInfo();
        try {
            DSysUser currentUser = currentUser();
            String url = "/sms/info/list?pageSize=10";
            if (!StringUtils.isEmpty(startDate)) {
                url += "&startDate=" + startDate;
            }
            if (!StringUtils.isEmpty(endDate)) {
                url += "&endDate=" + endDate;
            }
            if (currentPage != null) {
                url += "&currentPage=" + currentPage;
            }
            SmsInfo info11 = smsInfoService.getOne(id);
            BeanUtils.copyProperties(info11, info);
            if (!StringUtils.isEmpty(flag) && !"".equals(flag) && "groupSend".equals(flag)) {//判断转发跳转的是群发页面 还是单发页面
                pageUrl = "/pages/sms/sendGroupMessage";
                info.setSmsGroupId(null);
                List<SmsGroup> groupList = groupService.getAllGroupNoPage(currentUser.getId());
                model.addAttribute("groupList", groupList);
            } else {
                JSONArray treeObj = orgService.getOrgUserTree();
                model.addAttribute("tree", treeObj);
            }
            model.addAttribute("url", url);
            model.addAttribute("data", info);
            model.addAttribute("currentUser", currentUser);
            model.addAttribute("menus", listMenu());
            model.addAttribute("flagStr", flag);
            sysLogService.save(currentUser(), LOG_OPERATION_QUERY,
                    IPUtil.getIpAddr(request), "跳转发送页面", 1, "查询发件箱数据");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pageUrl;
    }

}
